package io.kimmking.chatoom.client.controller;

import io.kimmking.chatoom.client.boot.NettyClientBootStrap;
import io.kimmking.chatoom.client.config.Constant;
import io.kimmking.dubbo.common.entity.CharRoomMessage;
import io.kimmking.dubbo.common.service.CharRoomMessageService;
import io.kimmking.dubbo.common.service.charroom.CharRoomSelectorService;
import io.kimmking.dubbo.common.unit.ResponseResult;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/char/client")
public class SendMessageController {

    @DubboReference(version = "1.0.0")
    CharRoomSelectorService charRoomSelectorService;

    @Resource
    NettyClientBootStrap nettyClientBootStrap;

    @DubboReference(version = "1.0.0")
    CharRoomMessageService charRoomMessageService;

    @RequestMapping("/startClientBootStrap")
    public ResponseResult startBootstrap(){
        try {
            nettyClientBootStrap.startBootStrap(charRoomSelectorService);
            return ResponseResult.succeed("start nettyClientBootStrap success!");
        } catch (Exception e) {
            return ResponseResult.failed(e.getMessage());
        }
    }

    /**
     *  场景：客户端A向客户端B发送聊天消息
     *  1、客户端A主动将消息先发送到MQ队列
     *  2、<聊天服务>去消费MQ队列，将消息持久化存储(存储到Mysql)，然后去确认下客户端B是否在线
     *  3、
     *     1）当客户端B在线时，<聊天服务>将消息转发到MQ，然后<聊天服务>消费MQ将消费到的消息发送给NettyServer;
     *     2）如果客户端B不在线，<离线服务>就将消息存储至Redis(用来抗高并发)，当客户端B上线之后，将离线消息批量发送给NettyServer;
     *  4、NettyServer将接受到的消息推送给指定的客户端B
     *  5、客户端B收到消息之后，客户端B主动将成功响应的消息发送到MQ，然后<聊天服务>消费MQ里的成功响应消息，将Mysql里A发送的消息状态改为已接收状态；
     *
     * @param charRoomMessage 需要发送的消息体
     * @return
     */
    @PostMapping(value = "/sendMsg")
    public ResponseResult sendMsg(@RequestBody CharRoomMessage charRoomMessage){
        try {
            boolean result = charRoomMessageService.sendMessage(Constant.send_msg_topic, charRoomMessage);
            if (!result)
                return ResponseResult.failed("send message to MQ failed!");






//            nettyClientBootStrap.sendMessage(msg);
            return ResponseResult.succeed("send msg success");
        } catch (Exception e) {
            return ResponseResult.failed(e.getMessage());
        }
    }


}